package cn.gzsxt.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.annotation.SessionScope;

import cn.gzsxt.annotation.AdminSessionUpdate;
import cn.gzsxt.annotation.TokenForm;
import cn.gzsxt.service.AdminService;
import cn.gzsxt.service.DictionaryService;
import cn.gzsxt.service.RoleService;
import cn.gzsxt.utils.Global;
import cn.gzsxt.utils.Md5Utils;
import cn.gzsxt.utils.Page;

@Controller
@SessionScope
@RequestMapping(value = "/admin")
public class AdminController {

	private static final Logger LOGGER = LogManager.getLogger(AdminController.class);
	@Autowired
	private AdminService adminService;
	
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private RoleService roleService;



	/**
	 * 实现管理员增加
	 * @param entity
	 * @return
	 */
	@RequestMapping(value="/addAdmin")
	@TokenForm(remove=true)
	@AdminSessionUpdate
	public String  addAdmin(@RequestParam Map<String, Object> entity,HttpServletRequest request){
		LOGGER.debug("增加管理员"+entity);
		//创建时间
		entity.put("ADMIN_CREATE_DATE", new Date());
		//密码Md5加密
		entity.put("ADMIN_PWD",Md5Utils.md5((String)entity.get("ADMIN_PWD")));
	
		//将管理员的数据插入到数据库
		try {
			Map<String, Object> admin = adminService.addAdmin(entity);
			if (admin!=null) {
				request.setAttribute("admin_add_msg", "增加管理员成功");
			}else{
				request.setAttribute("admin_add_msg", "增加管理员失败");
			}
		} catch (Exception e) {
			request.setAttribute("admin_add_msg", "出现未知异常，请联系管理员");
			e.printStackTrace();
		}
		
		return "forward:/admin/toAdminAdd";
	}

	/**
	 * 删除管理员记录
	 * @param adminId
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deleteAdminById/{adminId}")
	@AdminSessionUpdate
	public String deleteAdminById(@PathVariable Long adminId,HttpServletRequest request){
		
		//通过Id删除记录
		adminService.deleteAdminByIds(adminId);
		
		//通过路径跳转回列表
		return "forward:/admin/toAdminList/0";
	}

	/**
	 * 批量删除多条数据
	 * @return
	 */
	@RequestMapping(value="/deleteAdminByIds")
	@AdminSessionUpdate
	public String deleteAdminByIds(String[] adminId){
		LOGGER.debug("批量删除管理员"+Arrays.toString(adminId));
		
		//通过管理员编好数组删除记录
		adminService.deleteAdminByIds((Object[])adminId);
		
		//通过路径跳转回列表
		return "forward:/admin/toAdminList/0";
	}

	/**
	 * 更新管理员记录
	 * @param entity
	 * @return
	 */
	@RequestMapping(value="/editAdmin")
	@AdminSessionUpdate
	public String editAdmin(@RequestParam Map<String, Object> entity,HttpServletRequest request){
		LOGGER.debug("更新管理员："+entity);
		entity.put("ADMIN_PWD", Md5Utils.md5((String)entity.get("ADMIN_PWD")) );
	
	
		try {
			Map<String, Object> admin = adminService.editAdmin(entity);
			if (admin!=null) {
				request.setAttribute("admin_edit_msg", "更新管理员成功");
				request.setAttribute("admin", admin);
			}else{
				request.setAttribute("admin_edit_msg", "更新管理员失败");
			}
		} catch (Exception e) {
			request.setAttribute("admin_edit_msg", "出现未知异常，请联系管理员");
			e.printStackTrace();
		}
		return "forward:/admin/toAdminEdit/"+entity.get("ADMIN_ID");
	}
	
	
	/**
	 * 修改密码
	 * 
	 * @param entity
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	@RequestMapping(value = "/editPassword")
	@AdminSessionUpdate
	public String editPassword(@RequestParam Map<String, Object> entity, HttpServletRequest request) {
		try {
			LOGGER.debug("修改管理员密码" + entity);
			// 业务逻辑的实现
			// 第一步：判断传递的原密码与当前登录会话里面的管理员密码是否一致

			String source = Md5Utils.md5((String) entity.get("SOURCE_PASSWORD"));
			HttpSession session = request.getSession();
			Map<String, Object> admin = (Map<String, Object>) session.getAttribute("admin");
			if (admin.get("ADMIN_PWD").equals(source)) {
				// 第二步：判断新密码与确认密码是否一致
				if (entity.get("NEW_PASSWORD").equals(entity.get("CONFIRM_PASSWORD"))) {

					// 第三步：如果确认信息正确，更新数据库里面的密码
					// 修改admin的密码,密码必须要md5加密
					admin.put("ADMIN_PWD", Md5Utils.md5((String) entity.get("NEW_PASSWORD")));
					Map<String, Object> resultAdmin = adminService.editAdminPassword(admin);
					if (resultAdmin != null) {
						session.setAttribute("admin", resultAdmin);
						request.setAttribute("admin_edit_password_msg", "修改密码成功");
					} else {
						request.setAttribute("admin_edit_password_msg", "修改密码失败！");
					}

				} else {
					request.setAttribute("admin_edit_password_msg", "两次密码输入不一致！");
				}

			} else {
				request.setAttribute("admin_edit_password_msg", "验证原密码不正确！");
			}
		} catch (Exception e) {
			request.setAttribute("admin_edit_password_msg", "出现未知异常，请联系管理员");
			e.printStackTrace();
		}

		return "manager/setting";
	}
	
	/**
	 * 用户登录
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/loginAdmin")
	public String loginAdmin(@RequestParam Map<String, Object> entity, HttpServletRequest request) {
		LOGGER.debug("管理员登录" + entity);
		// 将密码md5加密后在传递给Servic
		entity.put("ADMIN_PWD", Md5Utils.md5((String) entity.get("ADMIN_PWD")));
		LOGGER.debug("管理员登录-加密后的密码" + entity);
		try {
			Map<String, Object> admin = adminService.loginAdmin(entity);
			// 如果返回的不为null，表示登录成功
			if (admin != null) {
				// 登录成功，将管理员记录保存在会话里面
				HttpSession session = request.getSession();
				session.setAttribute("admin", admin);
				return "manager/index";
			} else {
				request.setAttribute("admin_login_msg", "账号或者密码不正确，请重新输入");
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("admin_login_msg", "出现未知异常（可能是用户已经被禁用），请联系管理员！");
		}

		// 跳回到登录页面
		return "forward:/login.jsp";
	}
	
	/**
	 * 跳转到管理员增加页面
	 * @return
	 */
	@RequestMapping(value="/toAdminAdd")
	@TokenForm(create=true)
	public String toAdminAdd(HttpServletRequest request){
		
		//获得管理员状态
		List<Map<String, Object>> adminStatuses = dictionaryService.findDictionaryByTypeCode("1001");
		request.setAttribute("adminStatuses", adminStatuses);
		
		
		//获得角色信息
		List<Map<String, Object>> roles = roleService.findAllRole();
		request.setAttribute("roles", roles);
		
		
		LOGGER.debug("跳转到管理员增加页面");
		return "manager/adminAdd";
	}
	
	/**
	 * 跳转到管理员编辑页面，编辑数据必须要标识唯一的记录
	 * 所以必须要传递一个管理员编号过来
	 * @return
	 */
	@RequestMapping(value="/toAdminEdit/{adminId}")
	public String toAdminEdit(@PathVariable Long adminId,HttpServletRequest request){
		LOGGER.debug("跳转到编辑管理员页面"+adminId);
		
		//获得管理员状态
		List<Map<String, Object>> adminStatuses = dictionaryService.findDictionaryByTypeCode("1001");
		request.setAttribute("adminStatuses", adminStatuses);
		
		
		//获得角色信息
		List<Map<String, Object>> roles = roleService.findAllRole();
		request.setAttribute("roles", roles);
		//跳转到编辑页面之前，需要将要编辑的管理员数据查询出来
		Map<String, Object> admin = adminService.findAdminById(adminId);
		request.setAttribute("admin", admin);
		
		return "manager/adminEdit";
	}
	
	/**
	 * 跳转到管理员列表页面
	 * @param index 数据库索引=页面索引-1。
	 * @param condition 查询的条件
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/toAdminList/{index}")
	public String toAdminList(@PathVariable Integer index,@RequestParam Map<String, Object> condition, HttpServletRequest request) {
		LOGGER.debug("跳转到管理员列表");
		if (index==null) {
			index=0;
		}
		//第一步：实现全部管理员数据查询
		Page page = adminService.findAdminByConditionToPage(condition, index, Global.RECORD_SIZE);
		//第二步：将数据通过作用域返回到页面
		request.setAttribute("adminPage", page);
		
		return "manager/adminList";
	}
	
	/**
	 * 跳转到密码页面
	 * 注意：http://localhost:8080/rabc-system/admin/toSetting/0
	 * 跳转密码后缀加0，是为了兼容其他请求路径的格式
	 * @return
	 */
	@RequestMapping(value = "/toSetting/0")
	public String toSetting() {

		return "manager/setting";
	}
	
	/**
	 * 管理员注销
	 * 
	 * @return
	 */
	@GetMapping(value = "/undoAdmin")
	public String undoAdmin(HttpSession session) {
		// 注销的业务逻辑
		// 第一步.判断session里面是否有管理员信息
		Object admin = session.getAttribute("admin");
		// 第二步.如果有管理员信息，就移除
		if (admin != null) {
			session.removeAttribute("admin");
		}
		// 第三步：重定向到登录页面，因为没有回传到页面的信息
		return "redirect:/login.jsp";
	}


}
